//
//  CameraViewController.m
//  哎游
//
//  Created by 刘建镇 on 15-1-6.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "macro.h"
#import "Masonry.h"
#import "CameraMenu.h"
#import "CameraViewController.h"

@interface CameraViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, CameraMenuDelegate>

@end

@implementation CameraViewController

- (void)dealloc
{
    [_imageView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        #define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
        [[NSLocale preferredLanguages] objectAtIndex:0]; 
    }
    return self;
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    NSLog(@"视图将要出现");
//
//    //这里先判断是否有相机，如果没有弹窗警告
//    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
//        CameraPickViewController *camera = [[CameraPickViewController alloc] init];
//        camera.sourceType = UIImagePickerControllerSourceTypeCamera;
//        [camera takePicture];
//        camera.videoQuality = UIImagePickerControllerQualityTypeLow;
//        if (_number >= 2) {
//            [camera removeFromParentViewController];
//            CameraPickViewController *camera = [[CameraPickViewController alloc] init];
//            camera.sourceType = UIImagePickerControllerSourceTypeCamera;
//            [camera takePicture];
//            camera.videoQuality = UIImagePickerControllerQualityTypeLow;
//            [self presentViewController:camera animated:YES completion:nil];
//            [camera release];
//            return;
//        }
//        [self presentViewController:camera animated:YES completion:nil];
//        [camera release];
//        _number++;
//    }else{
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//        [alert release];
//    }
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createMenu];
//    [self createView];
    self.targetURL = [[NSURL alloc] init];
    _isCamera = FALSE;
}

- (void)createMenu
{
    [self changeBackgroundImage];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.backgroundColor = [UIColor clearColor];
    _button.userInteractionEnabled = YES;
    [_button setTitle:@"Open Menu" forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _button.titleLabel.font = [UIFont fontWithName:@"GillSans-Light" size:25.0f];
    [_button addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_button];
    [_button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(0);
        make.centerY.equalTo(self.view.mas_centerY).offset(-145);
    }];

    
    UIButton *changeBackground = [UIButton buttonWithType:UIButtonTypeCustom];
    changeBackground.backgroundColor = [UIColor clearColor];
    changeBackground.imageView.userInteractionEnabled = YES;
    [changeBackground setTitle:@"Change Background" forState:UIControlStateNormal];
    [changeBackground setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    changeBackground.titleLabel.font = [UIFont fontWithName:@"GillSans-Light" size:15.0f];
    [changeBackground addTarget:self action:@selector(changeBackgroundImage) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:changeBackground];
    [changeBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX).offset(0);
        make.centerY.mas_equalTo(self.view.mas_centerY).offset(125);
    }];
}

- (void)showMenu {
//    NSLog(@"%@", CurrentLanguage);
//    if (CurrentLanguage == (id)"zh_Hans") {
//        NSLog(@"对了");
//    }
    NSArray *items = [[NSArray alloc] initWithObjects:@"Photo Library", @"Existing video", @"Take a Picture", nil];
    CameraMenu *menu = [[CameraMenu alloc] initWithItems:items parentView:self.view delegate:self];
    [menu show];
}

- (void)changeBackgroundImage {
//    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSUInteger random = arc4random_uniform(3) + 1;
    NSString *backgroundImage = [NSString stringWithFormat:@"screenshot-%lu.png", (unsigned long)random];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:backgroundImage]];
}

#pragma mark - BlurMenu Delegate
- (void)selectedItemAtIndex:(NSInteger)index {
    NSLog(@"Item selected at index %ld.", (long)index);
    switch (index) {
        case 0:
            [self openPhotos];
            break;
        case 1:
            [self showSavedVideo];
            break;
        case 2:
            [self showBothDevices];
            break;
    }
}

- (void)menuDidShow {
    NSLog(@"Menu appeared.");
}

- (void)menuDidHide {
    NSLog(@"Menu disappeared.");
}


- (void)createView
{
    self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _button.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [_button setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [_button setTitle:@"相册库" forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(openPhotos) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
    
    UIButton * videoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    videoButton.backgroundColor = [UIColor clearColor];
    //    but2.frame = CGRectMake(80, 350, 160, 40);
    videoButton.frame = CGRectMake(self.view.frame.size.width/5, self.view.frame.size.height - 100, 100, 40);
    [videoButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [videoButton setTitle:@"已存视频" forState:UIControlStateNormal];
    [videoButton addTarget:self action:@selector(showSavedVideo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:videoButton];
    
    UIButton * but2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    but2.backgroundColor = [UIColor clearColor];
//    but2.frame = CGRectMake(80, 350, 160, 40);
    but2.frame = CGRectMake(self.view.frame.size.width/2 +10, self.view.frame.size.height - 100, 100, 40);
    [but2 setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [but2 setTitle:@"拍照" forState:UIControlStateNormal];
    [but2 addTarget:self action:@selector(showBothDevices) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but2];
    
}

//打开保存的视频
- (void)showSavedVideo{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        self.imagePicker=[[UIImagePickerController alloc] init];
        _imagePicker.mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
        _imagePicker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
        _imagePicker.modalTransitionStyle=UIModalTransitionStylePartialCurl;
        [self presentViewController:_imagePicker animated:YES completion:nil];
        [_imagePicker release];
    }	
}

//打开相册库
- (void)openPhotos
{
    //这里先判断是否有相机，如果没有弹窗警告
    self.imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.allowsEditing = YES;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        _imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    }
    [self presentViewController:_imagePicker animated:YES completion:nil];
    [_imagePicker release];
}

//打开相机
- (void)showBothDevices
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.allowsEditing = YES;
    _isCamera = TRUE;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        _imagePicker.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        _imagePicker.videoQuality = UIImagePickerControllerQualityTypeLow;
        [self presentViewController:_imagePicker animated:YES completion:nil];
        [_imagePicker release];
    }else
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
//    [_imagePicker takePicture];
}

//UIImagePickerControllerDelegate的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"选取图片调用");
//    NSLog(@"info = %@", info);
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //判断是视频还是照片
    if ([mediaType isEqualToString:@"public.movie"]) {
        NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
        _targetURL = url;
        if (_isCamera) {
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library writeVideoAtPathToSavedPhotosAlbum:url completionBlock:nil];
            [library release];
//            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//另一种存照片的方式, 不用引入头文件
        }
        [self getPreViewImage:url];
    }
    //选取图片调用
    else if ([mediaType isEqualToString:@"public.image"]) {
        UIImage *image = [[info objectForKey:UIImagePickerControllerOriginalImage] retain];
        NSString *fileName = [[NSString alloc] init];
        if ([info objectForKey:UIImagePickerControllerReferenceURL]) {
            fileName = [[info objectForKey:UIImagePickerControllerReferenceURL] absoluteString];
            fileName = [self getFileName:fileName];
            
            //额外增加 可删
            UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:originalImage];
            UIScrollView *scrollView = [[UIScrollView alloc] init];
            [scrollView setScrollEnabled:YES];
            [scrollView setClipsToBounds:YES];
            [scrollView setBackgroundColor:[UIColor blackColor]];
            [scrollView setCanCancelContentTouches:NO];
            [scrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)];
            [scrollView addSubview:imageView];
            [imageView release];
            UIViewController *showImageController = [[UIViewController alloc] init];
            [showImageController setView:scrollView];
            [scrollView release];
            [picker pushViewController:showImageController animated:YES];
            [showImageController release];
        }else
        {
        //文件名 用时间+png来取名
        fileName = [self timeStampAsString];
        }
        NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
        [myDefault setValue:fileName forKey:@"fileName"];
        if (_isCamera) //判定, 避免重复保存,  🐔该照片是从相册里selected的, 不需要再保存
        {
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:nil];
            [library release];
        }
        [self performSelector:@selector(saveImage:) withObject:image afterDelay:0.0];
        [image release];
    }else
    {
        NSLog(@"Error media type");
        return;
    }
    _isCamera = FALSE;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"取消选取");
    _isCamera = FALSE;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 获取图片地址
- (void)getPreViewImage:(NSURL *)url   
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *gener = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gener.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gener copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    [self performSelector:@selector(saveImage:) withObject:img afterDelay:0.1];
    [img release];
}

#pragma mark 设置图片
- (void)saveImage:(UIImage *)image
{
    NSLog(@"review image");
    [_button setBackgroundImage:image forState:UIControlStateNormal];
}

#pragma mark 获取图片的文件名
- (NSString *)getFileName:(NSString *)fileName
{
    NSArray *temp = [fileName componentsSeparatedByString:@"&ext="];
    NSString *suffix = [temp lastObject];
    temp = [[temp objectAtIndex:0] componentsSeparatedByString:@"?id="];
    NSString *name = [temp lastObject];
    name = [name stringByAppendingFormat:@".%@", suffix];
    return name;
}

#pragma mark 文件名的格式
- (NSString *)timeStampAsString
{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dfm = [[NSDateFormatter alloc] init];
    [dfm setDateFormat:@"EEE-MMM-d"];
    NSString *locationString = [dfm stringFromDate:nowDate];
    return [locationString stringByAppendingString:@".png"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
